package web4;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.*;

@WebServlet("/ProductDownloadServlet")
public class ProductDownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getParameter("path");
        String realPath = getServletContext().getRealPath(path);

        // 设置响应内容类型
        response.setContentType("application/octet-stream");
        response.setContentLength((int) new File(realPath).length());

        // 设置下载文件的名称
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", new File(path).getName());
        response.setHeader(headerKey, headerValue);

        // 输出流
        OutputStream out = response.getOutputStream();
        try (InputStream in = new FileInputStream(realPath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        out.flush();
    }
}
